/*
' Copyright (c) 2011 DotNetNuke Corporation
'  All rights reserved.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
'
*/

using System;
using System.Globalization;
using System.Transactions;
using DotNetNuke.Common;
using DotNetNuke.Modules._2DoTasks.Components;
using DotNetNuke.Modules._2DoTasks.Components.Controllers;
using DotNetNuke.Modules._2DoTasks.Components.Entities;
using DotNetNuke.Modules._2DoTasks.Components.ExceptionHandling;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

namespace DotNetNuke.Modules._2DoTasks
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The Edit_2DoTasks class is used to manage content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Project : _2DoTasksModuleBase
    {
        #region "Properties"

        /// <summary>
        /// property for the current user, when editing a project if it's a manager or not
        /// </summary>
        public bool IsManager
        {
            get
            {
                if (ViewState["Project_IsManager"] != null)
                {
                    return Convert.ToBoolean(ViewState["Project_IsManager"]);
                }

                return false;
            }
            set
            {
                ViewState["Project_IsManager"] = value;
            }
        }

        /// <summary>
        /// returns the role to collect members from
        /// </summary>
        public string MemberRole
        {
            get
            {
                if (!string.IsNullOrEmpty(Convert.ToString(Settings["MemberRole"])))
                {
                    return Settings["MemberRole"].ToString();
                }

                return SettingsProjectList.DefaultRole;
            }
        }

        #endregion "Properties"

        #region Event Handlers

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                FillLanguages();

                //Implement your edit logic for your module
                if (!Page.IsPostBack)
                {
                    if (ProjectId.HasValue)
                    {
                        BindProject(ProjectId.Value);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// <summary>
        /// Adds/Updates an existing Project
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_send_Click(object sender, EventArgs e)
        {
            Nullable<DateTime> endDate;

            if (Page.IsValid)
            {
                try
                {
                    using (UnitOfWork uof = new UnitOfWork(PortalId, ModuleId))
                    {
                        if (ProjectParametersAreCorrectlyFilled(uof, out endDate))
                        {
                            using (TransactionScope scope = new TransactionScope())
                            {
                                ProjectController ProjectController = new ProjectController(uof);

                                //Set Project fields
                                _Project Project = new _Project
                                {
                                    Name = txt_Name.Text.Trim(),
                                    EndDate = endDate,
                                    Description = txt_description.Text.Trim()
                                };

                                if (ProjectId.HasValue)
                                {
                                    Project.Archived = chk_archived.Checked;
                                    Project.ProjectId = ProjectId.Value;
                                    ProjectController.Update(Project);
                                }
                                else
                                {
                                    ProjectController.Add(Project);
                                }
                                scope.Complete();
                            }

                            if (ProjectId.HasValue)
                                Response.Redirect(Globals.NavigateURL(string.Empty, string.Empty, "prj=2"));
                            else
                                Response.Redirect(Globals.NavigateURL(string.Empty, string.Empty, "prj=1"));
                        }
                    }
                }
                catch (ProjectValidationException exc)
                {
                    if (exc.StateOfError() == SharedEnum.CrudState.Insert)
                    {
                        ProjectController.InsertStatus status =
                            (ProjectController.InsertStatus)Enum.Parse(typeof(ProjectController.InsertStatus), exc.ErrorCode().ToString());

                        switch (status)
                        {
                            case ProjectController.InsertStatus.DUPLICATENAME:
                                Messages.ShowWarning(Localization.GetString("WarningDUPLICATENAME", this.LocalResourceFile));
                                break;

                            default:
                                Exceptions.LogException(exc);
                                Messages.ShowError(Localization.GetString("ErrorAddProject", this.LocalResourceFile));
                                break;
                        }
                    }
                    else if (exc.StateOfError() == SharedEnum.CrudState.Update)
                    {
                        ProjectController.UpdateStatus status =
                            (ProjectController.UpdateStatus)Enum.Parse(typeof(ProjectController.UpdateStatus), exc.ErrorCode().ToString());

                        switch (status)
                        {
                            case ProjectController.UpdateStatus.DUPLICATENAME:
                                Messages.ShowWarning(Localization.GetString("WarningDUPLICATENAME", this.LocalResourceFile));
                                break;

                            case ProjectController.UpdateStatus.NOTMANAGER:
                                Messages.ShowWarning(Localization.GetString("WarningNOTMANAGER", this.LocalResourceFile));
                                break;

                            default:
                                Exceptions.LogException(exc);
                                Messages.ShowError(Localization.GetString("ErrorUpdateProject", this.LocalResourceFile));
                                break;
                        }
                    }
                    else
                        throw exc;
                }
                catch (Exception exc)
                {
                    if (ProjectId.HasValue)
                        this.Messages.ShowError(Localization.GetString("ErrorUpdateProject", this.LocalResourceFile));
                    else
                        this.Messages.ShowError(Localization.GetString("ErrorAddProject", this.LocalResourceFile));

                    Exceptions.LogException(exc);
                }
            }
        }

        /// <summary>
        /// Deletes the current project
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                using (UnitOfWork uof = new UnitOfWork(PortalId, ModuleId))
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        ProjectController ProjectController = new ProjectController(uof);
                        ProjectController.Delete(new _Project { ProjectId = ProjectId.Value });

                        scope.Complete();
                        Response.Redirect(Globals.NavigateURL(string.Empty, string.Empty, "prj=3"));
                    }
                }
            }
            catch (ProjectValidationException exc)
            {
                ProjectController.DeleteStatus status =
                    (ProjectController.DeleteStatus)Enum.Parse(typeof(ProjectController.DeleteStatus), exc.ErrorCode().ToString());

                switch (status)
                {
                    case ProjectController.DeleteStatus.NOTMANAGER:
                        Messages.ShowWarning(Localization.GetString("WarningNOTMANAGER", this.LocalResourceFile));
                        break;

                    case ProjectController.DeleteStatus.PROJECTWITHTASKS:
                        Messages.ShowWarning(Localization.GetString("WarningPROJECTWITHTASKS", this.LocalResourceFile));
                        break;

                    default:
                        Exceptions.LogException(exc);
                        Messages.ShowError(Localization.GetString("ErrorDELETEProject", this.LocalResourceFile));
                        break;
                }
            }
            catch (Exception exc)
            {
                this.Messages.ShowError(Localization.GetString("ErrorDELETEProject", this.LocalResourceFile));

                Exceptions.LogException(exc);
            }
        }

        /// <summary>
        /// Close without making changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Globals.NavigateURL());
        }

        #endregion Event Handlers

        #region "Aux Functions"

        /// <summary>
        /// Evaluates if the fields for creating a new Project are correctly filled
        /// </summary>
        /// <returns>returns true, if ok, false otherwise</returns>
        private bool ProjectParametersAreCorrectlyFilled(
            UnitOfWork uof,
            out DateTime? out_endDate)
        {
            out_endDate = null;

            if (txt_Name.Text.Trim().Equals(string.Empty))
            {
                Messages.ShowWarning(Localization.GetString("ValidationNameRequired", this.LocalResourceFile));
                return false;
            }

            if (txt_Name.Text.Length < 2)
            {
                Messages.ShowWarning(Localization.GetString("ValidationNameMinLenght", this.LocalResourceFile));
                return false;
            }

            if (txt_endDate.Text != string.Empty)
            {
                try
                {
                    CultureInfo provider = CultureInfo.InvariantCulture;

                    out_endDate = DateTime.ParseExact(txt_endDate.Text, "dd-MM-yyyy", provider);
                }
                catch (Exception)
                {
                    Messages.ShowWarning(Localization.GetString("ValidationInvalidDate", this.LocalResourceFile));
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Binds the received Project id to the respective controls
        /// </summary>
        /// <param name="projectId">the project id</param>
        private void BindProject(int projectId)
        {
            using (UnitOfWork uof = new UnitOfWork(PortalId, ModuleId))
            {
                ProjectController prjCtrl = new ProjectController(uof);
                _Project project = prjCtrl.Get(projectId);
                if (project != null)
                {
                    txt_Name.Text = project.Name;
                    txt_description.Text = project.Description;
                    if (project.EndDate.HasValue)
                        txt_endDate.Text = project.EndDate.Value.ToString("dd-MM-yyyy");
                    this.ProjectMembers.Visible = true;

                    ProjectMemberController prjMbrCtrl = new ProjectMemberController(uof, projectId);
                    var manager = prjMbrCtrl.isCurrentUserManager();
                    IsManager = manager;
                    btn_send.Enabled = manager;
                    btn_delete.Visible = true;
                    pnl_archived.Visible = true;
                    chk_archived.Checked = project.Archived;

                    DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(btn_delete, Localization.GetString("DeleteConfirm", this.LocalResourceFile));
                }
                else
                {
                    Response.Redirect(Globals.NavigateURL(string.Empty, string.Empty));
                }
            }
        }

        /// <summary>
        /// Fills the language data into the respective controls
        /// </summary>
        private void FillLanguages()
        {
            btn_send.Text = Localization.GetString("btn_send", this.LocalResourceFile);
            btn_cancel.Text = Localization.GetString("btn_cancel", this.LocalResourceFile);

            txt_Name.CssClass = string.Concat("validate:{required:true, minlength: 2, messages:{required:'",
                                               Localization.GetString("ValidationNameRequired", this.LocalResourceFile),
                                                    "', minlength:'",
                                                    Localization.GetString("ValidationNameMinLenght", this.LocalResourceFile),
                                                    "'}}");
            btn_delete.Text = Localization.GetString("btn_delete", this.LocalResourceFile);
            chk_archived.Text = Localization.GetString("chk_archived", this.LocalResourceFile);
        }

        #endregion "Aux Functions"
    }
}